package com.qf.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;

import com.qf.config.AlipayConfig;
import com.qf.pojo.Order;
import com.qf.service.OrderService;
import com.qf.service.impl.OrderServiceImpl;

/**
 * 支付完成之后,同步页面通知的后端接口地址
 */
@WebServlet("/aliPayReturnUrlServlet")
public class AliPayReturnUrlServlet extends HttpServlet {


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		
		//获取支付宝GET过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map<String,String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用
			//System.out.println("转码前："+valueStr);
			params.put(name, valueStr);
		}
		
		
		try {
			//调用SDK验证签名
			boolean signVerified = AlipaySignature.rsaCheckV1(params,
					//验证支付宝的公钥
					AlipayConfig.alipay_public_key,
					//验证的编码格式
					AlipayConfig.charset,
					//验证的接口加签放SHA2
					AlipayConfig.sign_type);
			
			//——请在这里编写您的程序（以下代码仅作参考）——
			if(signVerified) {
				//商户订单号
				String out_trade_no =
						new String(request.getParameter("out_trade_no")); //订单编号获取
			
				//支付宝交易号
				String trade_no =
						new String(request.getParameter("trade_no"));
			
				//付款金额
				String total_amount =
						new String(request.getParameter("total_amount")) ;



				//自己的业务
				//获取订单编号--->调用订单业接口----获取订单---将订单的state设置1
				OrderService orderService = new OrderServiceImpl() ;
				Order order = orderService.getOrderByOid(out_trade_no);
				//更新订单状态
				order.setState(1) ;
				orderService.updateOrderState(order);


				//重定向到 成功页面
				request.setAttribute("out_trade_no",out_trade_no);
				request.getRequestDispatcher("/jsp/success.jsp").forward(request,response);




			}else {
				out.println("验签失败");
			}
			//——请在这里编写您的程序（以上代码仅作参考）——
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
